<template>
  <div class="orders">
    <el-card class="box-card" v-if="status === 'index'">
      <el-row>
        <el-input v-model="searchParams.order_no" placeholder="请输入订单编号" clearable style="width:200px"
          size="mini"></el-input>
        <el-input v-model="searchParams.userId" placeholder="请输入用户id" clearable style="width:150px"
          size="mini"></el-input>
        <el-select v-model="searchParams.status" placeholder="请选择订单状态" clearable style="width: 150px" size="mini">
          <el-option :value="item.id" v-for="item in statusArr" :key="item.id" :label="item.title"></el-option>
        </el-select>

        <el-select v-model="searchParams.payType" placeholder="请选择支付方式" clearable style="width: 150px" size="mini">
          <el-option :value="item.id" v-for="item in payTypeArr" :key="item.id" :label="item.title"></el-option>
        </el-select>
        <el-select v-model="searchParams.type" placeholder="请选择订单类型" clearable style="width: 150px" size="mini">
          <el-option :value="item.id" v-for="item in typeArr" :key="item.id" :label="item.title"></el-option>
        </el-select>
        <el-date-picker v-model="searchParams.startTime" type="date" value-format="yyyy-MM-dd" placeholder="选择起始时间"
          size="mini" style="width:150px"></el-date-picker>
        <el-date-picker v-model="searchParams.endTime" type="date" value-format="yyyy-MM-dd" placeholder="选择结束时间"
          size="mini" style="width:150px"></el-date-picker>
        <el-button type="info" icon="el-icon-refresh" size="mini" @click="reset"
          v-if="has('orders/index')">重置</el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getData"
          v-if="has('orders/index')">搜索</el-button>
        <!-- <el-button
          type="primary"
          icon="el-icon-upload"
          size="mini"
          @click="exportData"
          v-if="has('orders/export')"
          >导出</el-button
        >
        <el-upload
          :action="uploadUrl"
          :show-file-list="false"
          size="mini"
          :before-upload="uploadBefore"
          :on-success="uploadSuccess"
          style="display:inline-block"
        >
          <el-button size="mini" type="primary">发货</el-button>
        </el-upload> -->
      </el-row>

      <el-table :data="data.data" v-loading="table_loading" style="width: 100%;margin:10px auto" size="mini"
        :header-cell-style="{ background: '#f3f8fe', color: '#333' }">
        <el-table-column fixed prop="order_no" label="订单编号" align="center"></el-table-column>
        <el-table-column prop="total_amount" label="商品信息" align="center" width="130px">
          <template slot-scope="scope">
            <div style="display: flex;align-items: center;justify-content: space-between;">
              <el-image :src="scope.row.order_detail[0].goods_image" fit="contain" :style="{
                width: '50px',
                marginRight: '10px'
              }"></el-image>
              <div style="display: flex;flex-direction: column;">
                <div>{{ scope.row.order_detail[0].goods_name }}</div>
                <div>
                  ￥{{ scope.row.order_detail[0].goods_price }} x{{
                    scope.row.order_detail[0].num
                  }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="pay_amount" label="支付金额" align="center">
          <template slot-scope="scope">
            <div>运费：￥{{ scope.row.freight_amount }}</div>
            <div v-if="scope.row.type == 3">
              兑换币：{{ scope.row.exchange_amount }}
            </div>
            <div>实付款：￥{{ scope.row.pay_amount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center">
          <template slot-scope="scope">
            <span :style="{ color: getStatus(scope.row.status).color }">{{
              getStatus(scope.row.status).title
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.type == 2">支付</span>
            <span v-if="scope.row.type == 3">兑换</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.pay_type == 1" style="color:green">微信支付</span>
            <span v-if="scope.row.pay_type == 2" style="color:blue">支付宝支付</span>
            <span v-if="scope.row.pay_type == 3">余额兑换</span>
          </template>
        </el-table-column>
        <el-table-column prop="user.nickname" label="用户" align="center"></el-table-column>
        <el-table-column prop="created_at" label="创建时间" align="center"></el-table-column>

        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="cancel(scope.row.id)"
              v-if="has('orders/cancel') && scope.row.status > 1 && scope.row.status < 5">取消</el-button>
            <el-button type="primary" size="mini" @click="edit(scope.row.id)" v-if="has('orders/show')">详情</el-button>
            <el-button type="primary" size="mini" @click="showExpress(scope.row.id)"
              v-if="has('orders/update') && scope.row.status == 2">发货</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background style="text-align:center;margin:20px 0;" :current-page="searchParams.page"
        :page-sizes="pageSizes" layout="total,prev, pager, next,sizes" :total="data.total" @size-change="changeSize"
        @current-change="changePage"></el-pagination>
    </el-card>

    <!-- 详情 -->
    <el-drawer title="我是标题" :visible.sync="editStatus" :with-header="false" direction="rtl" size="40%">
      <div class="detail">
        <div class="detail_header">
          <img src="../../assets/order.png" class="detail_header_left" />
          <div class="detail_header_right">
            <div class="detail_header_right_top">
              <span v-if="editParams.type == 2">[在线支付]</span>
              <span v-if="editParams.type == 3">[货币兑换]</span>
            </div>
            <div class="detail_header_order_sn">
              订单编号：{{ editParams.order_no }}
              <i class="el-icon-copy-document" style="cursor: pointer" @click="copy(editParams.order_no)"></i>
            </div>
          </div>
        </div>
        <div class="detail_bottom">
          <div class="detail_bottom_item">
            <div class="detail_bottom_item_title">订单状态</div>
            <div :style="{ color: getStatus(editParams.status).color }" class="detail_bottom_item_content">
              {{ getStatus(editParams.status).title }}
            </div>
          </div>
          <div class="detail_bottom_item">
            <div class="detail_bottom_item_title">实际支付</div>
            <div class="detail_bottom_item_content" v-if="editParams.pay_type" style="color:red">
              ￥{{ editParams.pay_amount }}
            </div>
            <div class="detail_bottom_item_content" v-else>-</div>
          </div>
          <div class="detail_bottom_item">
            <div class="detail_bottom_item_title">支付方式</div>
            <div class="detail_bottom_item_content" v-if="editParams.pay_type">
              {{ getPay(editParams.pay_type).title }}
            </div>
            <div class="detail_bottom_item_content" v-else>-</div>
          </div>
          <div class="detail_bottom_item">
            <div class="detail_bottom_item_title">支付时间</div>
            <div class="detail_bottom_item_content" v-if="editParams.paid_at">
              {{ editParams.paid_at }}
            </div>
            <div class="detail_bottom_item_content" v-else>-</div>
          </div>
        </div>
      </div>
      <el-tabs v-model="edit_type" type="card">
        <el-tab-pane label="订单信息" name="1">
          <div class="tab_item">
            <div class="tab_title">
              <i class="el-icon-user-solid" style="color: #409eff"></i> 用户信息
            </div>
            <div class="tab_content">
              <div class="tab_content_item">
                用户ID：{{ editParams.user_id }}
                <i class="el-icon-copy-document" style="cursor: pointer" @click="copy(editParams.user_id)"></i>
              </div>
              <div class="tab_content_item">
                用户昵称：{{ editParams.user.nickname }}
              </div>
              <div class="tab_content_item">
                手机号：{{ editParams.user.mobile }}
              </div>
            </div>
          </div>
          <el-divider></el-divider>
          <div class="tab_item">
            <div class="tab_title">
              <i class="el-icon-truck" style="color: #409eff"></i> 收货信息
            </div>
            <div class="tab_content">
              <div class="tab_content_item">
                收货人：{{ editParams.order_username }}
              </div>
              <div class="tab_content_item">
                收货电话：{{ editParams.order_mobile }}
              </div>
              <div class="tab_content_item">
                收货地址：{{ editParams.order_address }}
              </div>
            </div>
          </div>
          <el-divider></el-divider>

          <div class="tab_item">
            <div class="tab_title">
              <i class="el-icon-s-order" style="color: #409eff"></i> 订单信息
            </div>
            <div class="tab_content">
              <div class="tab_content_item tab_content_item_flex">
                <span class="tab_content_item_flex_left">订单状态：<span
                    :style="{ color: getStatus(editParams.status).color }">{{ getStatus(editParams.status).title
                    }}</span></span>
                <span class="tab_content_item_flex_right">用户备注：<span>{{ editParams.remark }}</span></span>
              </div>
              <div class="tab_content_item tab_content_item_flex">
                <span class="tab_content_item_flex_left">商品总额：<span>{{ editParams.total_amount }}</span></span>
                <span class="tab_content_item_flex_right">下单时间：<span>{{ editParams.created_at }}</span></span>
              </div>
              <div class="tab_content_item tab_content_item_flex">
                <span class="tab_content_item_flex_left">优惠券：<span>{{ editParams.coupon_amount }}</span></span>
                <span class="tab_content_item_flex_right">实付款：<span v-if="editParams.pay_amount" style="color:red">￥{{
                    editParams.pay_amount }}</span><span v-else>-</span></span>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品信息" name="2">
          <el-table :data="editParams.order_detail" style="width: 100%" size="mini"
            :header-cell-style="{ background: '#f3f8fe', color: '#333' }">
            <el-table-column prop="id" label="商品ID" align="center">
              <template slot-scope="scope">
                <i class="el-icon-copy-document" style="cursor: pointer" @click="copy(scope.row.goods_id)"></i>
                <span>{{ scope.row.goods_id }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品主图" align="center">
              <template slot-scope="scope">
                <el-image :src="scope.row.goods_image" :style="{
                  width: '50px',
                  height: '50px',
                  borderRadius: '5px'
                }"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="goods_name" label="商品名称" align="center"></el-table-column>

            <el-table-column prop="attr_values" label="商品属性" align="center"></el-table-column>

            <el-table-column prop="goods_price" label="商品金额" align="center"></el-table-column>

            <el-table-column prop="num" label="数量" align="center"></el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="发货记录" name="3">
          <div v-if="!editParams.order_express" style="color:red;margin;10px auto;text-align:center">
            暂未发货！
          </div>
          <el-table v-else :data="editParams.order_express" style="width: 100%" size="mini"
            :header-cell-style="{ background: '#f3f8fe', color: '#333' }">
            <el-table-column prop="express_name" label="快递公司" align="center"></el-table-column>

            <el-table-column prop="express_no" label="快递单号" align="center">
              <template slot-scope="scope">
                <i class="el-icon-copy-document" style="cursor: pointer" @click="copy(scope.row.express_no)"></i>
                <span>{{ scope.row.express_no }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="created_at" label="发货时间" align="center"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <!-- 发货弹窗 -->
    <el-dialog title="发货" :visible.sync="expressStatus">
      <div v-for="(item, index) in expressParams" :key="index">
        <div>
          <span>包裹{{ index + 1 }}</span>
          <el-button size="mini" type="danger" @click="delExpress(index)">删除</el-button>
        </div>
        <div style="margin-top:10px">
          快递单号：
          <el-input v-model="item.express_no" autocomplete="off" placeholder="请输入快递单号" style="width:200px"
            size="small"></el-input>
          快递名称：
          <el-select size="small" v-model="item.express_name" placeholder="请选择快递">
            <el-option :label="key.name" :value="key.name" v-for="key in expressArr" :key="key.id"></el-option>
          </el-select>
        </div>

        <el-divider></el-divider>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addExpress()" icon="el-icon-circle-plus">添加包裹</el-button>
        <el-button type="primary" @click="submitExpress()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from "../../api/api.js";
export default {
  name: "order",
  data() {
    return {
      x: 100,
      status: "index", // 页面控制
      data: [], // 表格诗句
      table_loading: true, // 表格加载中
      loading: false, // 全局加载中
      uploadUrl: "admin/orders/import", // 上传地址,
      statusArr: [
        { id: 1, title: "待支付", color: "#409EFF" },
        { id: 2, title: "待发货", color: "#F56C6C" },
        { id: 3, title: "待收货", color: "#E6A23C" },
        { id: 4, title: "已完成", color: "#67C23A" },
        { id: 5, title: "交易关闭", color: "#67C23A" },
        { id: 6, title: "已取消", color: "#409EFF" }
      ],
      payTypeArr: [
        { id: 1, title: "微信支付", color: "#409EFF" },
        { id: 2, title: "支付宝支付", color: "#F56C6C" },
        { id: 3, title: "余额兑换", color: "#E6A23C" }
      ],
      typeArr: [
        { id: 2, title: "支付", color: "#F56C6C" },
        { id: 3, title: "兑换", color: "#E6A23C" }
      ],
      edit_type: "1",
      pageSizes: [10, 20, 50, 100, 200, 500, 800, 1000, 2000], // 每页条数默认10
      express_loading: false,
      searchParams: {
        // 搜索参数
        orderNo: "",
        page: 1,
        limit: 10,
        startTime: "",
        endTime: "",
        userId: "",
        status: "",
        type: "",
        payType: ""
      },

      expressArr: [],
      expressStatus: false,
      idArr: [],
      expressData: [],
      editParams: {
        id: 0,
        status: 1,
        type: 2,
        pay_type: 1,
        user: {}
      },
      editStatus: false,

      expressParams: [
        {
          express_no: "",
          express_name: ""
        }
      ]
    };
  },
  created() {
    this.getData();
    this.getExpress();
  },
  methods: {
    addExpress() {
      this.expressParams.push({ express_no: "", express_name: "" });
    },
    delExpress(index) {
      if (this.expressParams.length == 1) {
        this.$message.info("至少有一个包裹");
        return;
      }
      this.expressParams.splice(index, 1);
    },
    // 复制订单编号
    copy(content) {
      if (window.clipboardData) {
        window.clipboardData.setData("text", content);
      } else {
        (function (content) {
          //oncopy 事件在用户拷贝元素上的内容时触发。
          document.oncopy = function (e) {
            e.clipboardData.setData("text", content);
            e.preventDefault(); //取消事件的默认动作
            document.oncopy = null;
          };
        })(content);
        document.execCommand("Copy");
      }
      this.$message.success("复制成功");
    },
    // 发货成功
    uploadSuccess(res) {
      this.$message.success(res.msg);
      this.init();
      this.express_loading.close();
      this.getData();
    },
    uploadBefore() {
      this.express_loading = this.$loading({
        lock: true,
        text: "发货中请勿操作",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    submitExpress() {
      if (this.expressParams.length == 0) {
        this.$message.error("至少一个包裹");
        return;
      }

      for (var i = 0; i < this.expressParams.length; i++) {
        if (
          !this.expressParams[i].express_name ||
          !this.expressParams[i].express_no
        ) {
          this.$message.error("请完善表单");
          return;
        }
      }
      this.load();
      api.orders
        .edit(this.expressParams.id, { expressParams: this.expressParams })
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.reset();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 获取支付类型
    getPay(status) {
      for (let i = 0; i < this.payTypeArr.length; i++) {
        if (this.payTypeArr[i].id == status) {
          return this.payTypeArr[i];
        }
      }
      return { id: 0, title: "未支付", color: "red" };
    },
    // 获取订单状态
    getStatus(status) {
      for (let i = 0; i < this.statusArr.length; i++) {
        if (this.statusArr[i].id == status) {
          return this.statusArr[i];
        }
      }
    },
    // 查看所有快递
    getExpress() {
      api.common.express().then(res => {
        if (res.data.code === 200) {
          this.expressArr = res.data.data;
          console.log(this.expressArr);
        }
      });
    },
    exportData() {
      if (!this.idArr.length) {
        this.$message.info("请先选择要导出的数据");
        return false;
      }
      window.open(`/admin/orders/export?id=${this.idArr}`);
    },
    showExpress(id) {
      this.expressStatus = true;
      this.expressParams.id = id;
    },
    selection(value) {
      this.idArr = [];
      value.forEach(item => {
        this.idArr.push(item.id);
      });
    },
    // 获取选择的title
    selectExpress(e) {
      const index = this.expressArr.findIndex(item => {
        return item.value === e;
      });
      this.editParams.express_title = this.expressArr[index].title;
    },
    // 确认发货
    express() {
      if (!this.editParams.express_no) {
        this.$message.error("请输入快递单号");
        return false;
      }
      if (!this.editParams.express_value) {
        this.$message.error("请选择快递名称");
        return false;
      }
      api.orders
        .edit(this.editParams.id, {
          express_no: this.editParams.express_no,
          express_title: this.editParams.express_title,
          express_value: this.editParams.express_value
        })
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success("发货成功");
            this.edit(this.editParams.id);
          }
        });
    },
    // 加载中
    load() {
      this.loading = this.$loading({
        lock: true,
        text: "数据加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    // 取消加载
    unload() {
      this.loading.close();
    },
    // 获取所有订单
    getData() {
      this.table_loading = true;
      api.orders
        .index({ params: this.searchParams })
        .then(res => {
          if (res.data.code === 200) {
            this.table_loading = false;
            this.data = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 重置搜索参数重新搜索
    reset() {
      this.init();
      this.getData();
    },
    // 初始化
    init() {
      this.searchParams.orderNo = "";
      this.searchParams.startTime = "";
      this.searchParams.endTime = "";
      this.searchParams.status = "";
      this.searchParams.userId = "";
      this.status = "index";
      this.expressStatus = false;
      this.expressParams = [{ express_name: "", express_no: "" }];
    },
    // 改变每页条数时
    changeSize(limit) {
      this.searchParams.limit = limit;
      this.getData();
    },
    // 改变当前页码时
    changePage(page) {
      this.searchParams.page = page;
      this.getData();
    },
    //取消订单
    cancel(id, index) {
      this.$confirm("此操作将永久取消该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          this.load();
          api.orders
            .cancel(id)
            .then(res => {
              this.unload();
              if (res.data.code === 200) {
                this.$message({
                  type: "success",
                  message: "取消成功!"
                });
                this.data.data.splice(index, 1);
                this.data.total--;
              }
            })
            .catch(error => {
              console.log(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    // 详情页面
    edit(id) {
      api.orders
        .show(id)
        .then(res => {
          if (res.data.code === 200) {
            this.editParams = res.data.data;
            this.editStatus = true;
          }
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
};
</script>

<style scoped lang="less">
.orders {
  margin: 0 auto;

  .search {
    margin: 0 auto 10px auto;
  }

  .block {
    margin-bottom: 10px;

    padding-left: 10px;
    border-left: 5px solid #ccc;
    background: #f5f8fc;
    height: 50px;
    line-height: 50px;
    color: #ccc;
  }

  .timeline {
    padding: 10px;
  }

  .goods {
    display: flex;
    border: 1px solid #ccc;
    padding: 10px;
    margin: 10px 0;

    .goods_image {
      width: 120px;
      height: 120px;
      border-radius: 5px;
      margin-right: 20px;
    }

    .goods_info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      .goods_amount {
        display: flex;
        align-items: center;

        .amount {
          color: red;
          margin-right: 20px;
        }
      }
    }
  }

  .address {
    .order_username {
      margin: 10px 0;
    }
  }
}

.detail {
  margin-top: 10px;

  .detail_header {
    display: flex;
    height: 50px;
    align-items: center;

    .detail_header_left {
      margin-right: 15px;
      width: 60px;
      height: 50px;
    }

    .detail_header_right {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 50px;

      .detail_header_right_top {
        color: #666;
      }

      .detail_header_order_sn {
        color: #999;
        font-size: 12px;
      }
    }
  }

  .detail_bottom {
    display: flex;
    justify-content: space-between;
    margin: 10px;

    .detail_bottom_item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-around;
      height: 50px;

      .detail_bottom_item_title {
        color: #666;
        font-size: 12px;
      }

      .detail_bottom_item_content {
        font-size: 12px;
      }
    }
  }
}

.tab_item {
  margin-left: 10px;

  .tab_title {
    // font-size: 18px;
    margin-bottom: 10px;
    color: #409eff;
  }

  .tab_content {
    font-size: 14px;

    .tab_content_item {
      margin-top: 10px;
    }

    .tab_content_item_flex {
      display: flex;

      .tab_content_item_flex_left {
        width: 200px;
      }

      .tab_content_item_flex_right {
        flex: 1;
      }
    }

    .remark {
      margin: 10px;
    }
  }
}
</style>
